package model

import (
	"fmt"
	"time"

	"gorm.io/gorm"
)

// Order 订单表
type Order struct {
	ID        int64          `gorm:"primaryKey;autoIncrement" json:"id"`
	OrderNo   string         `gorm:"type:varchar(50);uniqueIndex;not null;comment:订单号" json:"orderNo"`
	UserID    int64          `gorm:"index;not null;comment:用户ID" json:"userId"`
	OrderType int            `gorm:"type:tinyint;not null;comment:订单类型 1:预约 2:问诊 3:开药" json:"orderType"`
	Status    int            `gorm:"type:tinyint;default:1;comment:订单状态 1:待支付 2:已支付 3:已取消 4:已完成 5:已退款" json:"status"`
	Amount    float64        `gorm:"type:decimal(10,2);not null;comment:订单金额" json:"amount"`
	RelatedID int64          `gorm:"comment:关联ID（预约ID、问诊ID、处方ID）" json:"relatedId"`
	Remark    string         `gorm:"type:varchar(500);comment:备注" json:"remark"`
	CreatedAt time.Time      `json:"createdAt"`
	UpdatedAt time.Time      `json:"updatedAt"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}

func (Order) TableName() string {
	return "orders"
}

// ==================== 模型方法 ====================

// GenerateOrderNo 生成订单号
func GenerateOrderNo(orderType int) string {
	now := time.Now()
	return fmt.Sprintf("%d%s%06d", orderType, now.Format("20060102150405"), now.UnixNano()%1000000)
}

// Create 创建订单
func (o *Order) Create(db *gorm.DB) error {
	if o.OrderNo == "" {
		o.OrderNo = GenerateOrderNo(o.OrderType)
	}
	o.CreatedAt = time.Now()
	o.UpdatedAt = time.Now()
	return db.Create(o).Error
}

// GetByID 根据ID获取订单
func (o *Order) GetByID(db *gorm.DB, id, userID int64) error {
	return db.Where("id = ? AND user_id = ?", id, userID).First(o).Error
}

// GetByOrderNo 根据订单号获取订单
func (o *Order) GetByOrderNo(db *gorm.DB, orderNo string) error {
	return db.Where("order_no = ?", orderNo).First(o).Error
}

// GetListByUserID 获取用户的订单列表
func GetOrderListByUserID(db *gorm.DB, userID int64, orderType, page, pageSize int) ([]Order, int64, error) {
	var orders []Order
	var total int64

	query := db.Model(&Order{}).Where("user_id = ?", userID)
	if orderType > 0 {
		query = query.Where("order_type = ?", orderType)
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	err := query.Scopes(Paginate(page, pageSize)).
		Order("id DESC").
		Find(&orders).Error

	return orders, total, err
}

// UpdateStatus 更新订单状态
func (o *Order) UpdateStatus(db *gorm.DB, status int) error {
	return db.Model(o).Updates(map[string]interface{}{
		"status":     status,
		"updated_at": time.Now(),
	}).Error
}

// Cancel 取消订单
func (o *Order) Cancel(db *gorm.DB) error {
	return db.Model(o).Updates(map[string]interface{}{
		"status":     3, // 已取消
		"updated_at": time.Now(),
	}).Error
}
